package cn.yx.framework.error;

import cn.com.yx.ms.service.ILogService;
import cn.com.yx.ms.service.IUserContextService;
import cn.yx.framework.view.OutViewer;
import com.alibaba.fastjson.JSON;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * Created by Administrator on 2017-02-10.
 */
@RequestMapping({"error"})
public class ServerExceptionHandler implements ErrorController {

    @Resource
    private ILogService iLogService;
    @Resource
    private IUserContextService iUserContextService;

    public ServerExceptionHandler() {
    }

    public String getErrorPath() {
        return null;
    }

    @RequestMapping
    public void error(HttpServletRequest request, HttpServletResponse response) {
        final HttpStatus status = this.getStatus(request);
        OutViewer.out(request, response, new HashMap() {
            {
                this.put("code", Integer.valueOf(status.value()));
                this.put("msg", OutViewer.getMessage(status));
            }
        });

        //全局异常捕获并记录
        iLogService.log("error",
                "系统异常",
                OutViewer.getMessage(status),
                "0");
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        } else {
            try {
                return HttpStatus.valueOf(statusCode.intValue());
            } catch (Exception var4) {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }
        }
    }
}
